<template>
  <div class="app-container search-list">
    <table-pagination
        ref="el-search-table"
        :adaptive="fixOption"
        :columns="columns"
        :fetch="getData"
        :form-options="formOptions"
        :page-sizes="[20, 50, 100]"
        height="300"
        list-field="records"
        method="get"
        page-index-key="page"
        page-size-key="pageSize"
        total-field="totalElements"
        type="remote">
      <template #button>
        <el-button icon="el-icon-circle-plus" size="mini" type="primary" @click="handleAdd">新增</el-button>
      </template>
      <el-table-column slot="append" label="操作" width="400" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status=='not_start'" plain size="mini" type="primary"
                     @click="handlePublish(scope.row.id)">发布</el-button>
          <el-button v-if="scope.row.status=='ing'" plain size="mini" type="primary"
                     @click="handlePause(scope.row.id)">暂停</el-button>
          <el-button v-if="scope.row.status=='pause'" plain size="mini" type="primary"
                     @click="handleRecover(scope.row.id)">恢复</el-button>
          <el-button v-if="scope.row.status!='end'" plain size="mini" type="primary"
                     @click="handlePreview(scope.row.id)">预览</el-button>
          <el-button v-if="scope.row.status!='end'" plain size="mini" type="primary"
                     @click="handleEdit(scope.row.id)">编辑</el-button>
          <el-button v-if="scope.row.status!=='end'" plain size="mini" type="primary"
                     @click="handleCopy(scope.row.id)">复制</el-button>
          <el-button plain size="mini" type="danger" @click="deleteActivityView(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <template slot="statusText" slot-scope="scope">
        <span v-if="scope.row.status=='not_start'" style="color: rgb(255,153,0)">{{scope.row.statusText}}</span>
        <span v-if="scope.row.status=='ing'"style="color: rgb(0,128,0)">{{scope.row.statusText}}</span>
        <span v-if="scope.row.status=='end'"style="color: rgb(153,153,153)">{{scope.row.statusText}}</span>
        <span v-if="scope.row.status=='pause'"style="color: rgb(255,0,0)">{{scope.row.statusText}}</span>
      </template>
    </table-pagination>
    <!-- 预览弹窗 -->
    <div @click="dialogTableVisible=false">
      <el-dialog :visible.sync="dialogTableVisible" customClass="customWidth" :close-on-click-modal="false" >
        <component :is="previewName" :formData="formData" @close="dialogTableVisible=false" :isPreview="true"></component>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import {
    getActivityViewPage, deleteActivityView, editActivityView, getActivityViewDetail,
    recoverActivityView, pauseActivityView, publishActivityView
} from '@/api/marketing';
import {utcFormat} from '@/utils/filters';
import {mapGetters} from 'vuex';
import Subscription from '@/components/theme-editor/viewComponents/Subscription/SubscriptionPopups2/View';
import ReductionActivity from '@/components/theme-editor/viewComponents/Subscription/SubscriptionPopups1/View';
import MarketingActivities from '@/components/theme-editor/viewComponents/Subscription/MarketingActivities/View';
import FlashSale from '@/components/theme-editor/viewComponents/Subscription/FlashSale/View';
import BulletinBoardCountDown from '@/components/theme-editor/viewComponents/Subscription/BulletinBoardCountDown/View';
import BulletinBoardReduction from '@/components/theme-editor/viewComponents/Subscription/BulletinBoardReduction/View';
import {getPriceReducePage} from '@/api/priceReduce';

export default {
    name: 'activity-view',
    components: {TablePagination, ReductionActivity, MarketingActivities, FlashSale, BulletinBoardCountDown, BulletinBoardReduction, Subscription},
    data () {
        return {
            statusList: [
                {'label': '未开始', 'value': 'not_start'},
                {'label': '进行中', 'value': 'ing'},
                {'label': '已暂停', 'value': 'pause'},
                {'label': '已结束', 'value': 'end'}
            ],
            fixOption: {fixedHeader: true},
            pageParams: {
                page: 1,
                pageSize: 20,
                name: '',
                activityStatus: '',
                activityTemplate: ''
            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: [
                    {prop: 'name', label: '活动名称：', placeholder: '请输入活动名称'},
                    {
                        prop: 'activityTemplate',
                        label: '活动类型：',
                        itemType: 'select',
                        placeholder: '请选择类型',
                        selectFetch: () => {
                            return new Promise((resolve, reject) => {
                                resolve(this.templateList);
                            });
                        }
                    },
                    {
                        prop: 'activityStatus',
                        label: '活动状态：',
                        itemType: 'select',
                        placeholder: '请选择状态',
                        selectFetch: () => {
                            return new Promise((resolve, reject) => {
                                resolve(this.statusList);
                            });
                        }
                    }
                ]
            },
            columns: [
                {label: '名称', prop: 'name', showOverflowTooltip: true},
                {
                    label: '活动类型',
                    prop: 'activityTemplate',
                    render: row => {
                        let tempVal = this.activityTemplate[row.activityTemplate];
                        if (tempVal) {
                            return tempVal;
                        }
                        return '';
                    }
                },
                {
                    label: '弹窗公告',
                    prop: 'showType',
                    width: 100,
                    render: row => {
                        if (row.showType === 'dialog') {
                            return '弹窗';
                        }
                        if (row.showType === 'notice') {
                            return '公告';
                        }
                        return '';
                    }
                },
                {
                    label: '有效时间',
                    prop: 'startTime',
                    width: 300,
                    render: row => {
                        let startTime = utcFormat(row.startTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                        let finishTime = '永不过期';
                        if (row.finishTime) {
                            finishTime = utcFormat(row.finishTime, 'YYYY-MM-DD HH:mm:ss', this.timeZone);
                        }
                        return startTime + ' ~ ' + finishTime;
                    }
                },
                {label: '曝光次数', prop: 'showTimes'},
                {label: '参与次数', prop: 'attendTimes'},
                {
                    label: '转化率',
                    prop: 'convertRate',
                    render: row => {
                        if (row.showTimes === undefined || row.attendTimes === undefined) {
                            return '';
                        }
                        if (row.showTimes === 0 || row.attendTimes === 0) {
                            return '';
                        }
                        return (row.attendTimes / row.showTimes * 100).toFixed(2) + '%';
                    }
                },
                {label: '状态', slotName: 'statusText'}
            ],
            previewName: '',
            formData: {},
            activityTemplate: {
                'ReductionActivity': '满减活动',
                'MarketingActivities': '营销活动',
                'FlashSale': '限时活动',
                'BulletinBoardCountDown': '活动倒计时',
                'BulletinBoardReduction': '满减提醒'
            },
            templateList: [
                {'label': '满减活动', 'value': 'ReductionActivity'},
                {'label': '营销活动', 'value': 'MarketingActivities'},
                {'label': '限时活动', 'value': 'FlashSale'},
                {'label': '活动倒计时', 'value': 'BulletinBoardCountDown'},
                {'label': '满减提醒', 'value': 'BulletinBoardReduction'}
            ],
            dialogTableVisible: false
        };
    },
    methods: {
        getData (params) {
            params.siteId = this.siteId;
            return new Promise((resolve, reject) => {
                getActivityViewPage(params).then((res) => {
                    resolve(res);
                });
            });
        },
        handleSearch () {
            this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
        },
        // 新建弹窗通告
        handleAdd () {
            this.$router.push({name: 'activity-view-add'});
        },
        handleCopy (id) {
            this.$router.push({name: 'activity-view-copy', params: {id}});
        },
        handleEdit (id) {
            this.$router.push({name: 'activity-view-edit', params: {id}});
        },
        handlePublish (id) {
            let siteId = this.siteId;
            this.$confirm('此操作将发布弹窗公告, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                publishActivityView(siteId, id).then(res => {
                    if (res.code === '200') {
                        this.$message({ type: 'success', message: '发布成功!' });
                        this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    } else {
                        this.$message({ type: 'error', message: res.message });
                    }
                });
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消操作' });
            });
        },
        handlePreview (id) {
            getActivityViewDetail(this.siteId, id).then(res => {
                const {data} = res;
                this.previewName = data.activityTemplate;
                this.formData = JSON.parse(data.settings);
                if (this.formData.levelJson) {
                    let formParams = {
                        name: '',
                        page: 1,
                        pageSize: 20,
                        status: 'unfinished'
                    };
                    getPriceReducePage({...formParams, siteId: this.siteId}).then(res => {
                        this.dialogTableVisible = true;
                        let row = res.records.find(res => res.id === this.formData.priceReduceId);
                        this.formData.levelJson = JSON.parse(row.levelJson);
                    });
                } else {
                    this.dialogTableVisible = true;
                }
            });
        },
        handlePause (id) {
            let siteId = this.siteId;
            this.$confirm('此操作将暂停弹窗公告, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                pauseActivityView(siteId, id).then(res => {
                    if (res.code === '200') {
                        this.$message({ type: 'success', message: '暂停成功!' });
                        this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    } else {
                        this.$message({ type: 'error', message: res.message });
                    }
                });
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消操作' });
            });
        },
        handleRecover (id) {
            let siteId = this.siteId;
            this.$confirm('此操作将恢复暂停弹窗公告, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                recoverActivityView(siteId, id).then(res => {
                    if (res.code === '200') {
                        this.$message({ type: 'success', message: '恢复成功!' });
                        this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    } else {
                        this.$message({ type: 'error', message: res.message });
                    }
                });
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消操作' });
            });
        },
        deleteActivityView (id) {
            let siteId = this.siteId;
            this.$confirm('此操作将删除弹窗公告, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteActivityView(siteId, id).then(res => {
                    if (res.code === '200') {
                        this.$message({ type: 'success', message: '删除成功!' });
                        this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                    } else {
                        this.$message({ type: 'error', message: res.message });
                    }
                });
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消操作' });
            });
        }
    },
    computed: {
        ...mapGetters(['timeZone']),
        siteId () {
            return this.$store.state.user.siteId;
        }
    }
}
;
</script>

<style lang="scss" scoped>
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

.Template6__layer {
  position: absolute!important;
  width: 60% !important;
  height: 90% !important;
}

.draggableItem {
  width: 100%;
}
.Template8__layer {
  background-color: transparent!important;
  padding: 15vh 0;
}
//满减提醒
.Banner6__layer {
  position: relative!important;
}
// 活动倒计时
.Banner3__layer {
  position: relative!important;
}

</style>

<style lang="scss">
.customWidth {
  box-sizing: border-box!important;
  width:100%;
  height: 100%;
  margin: 0!important;
  background-color: transparent;
  .el-dialog__header  {
    padding: 0;
    .el-dialog__headerbtn{
      color: #fff;
      font-size: 24px;
      font-weight: bold;
      z-index: 99;
      .el-dialog__close{
        color: inherit;
      }
    }
  }
  .el-dialog__body  {
    padding: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
    .Banner3__layer{
      height: auto;
    }
  }
}
//限时促销
.Template8PcWrap {
  position: relative!important;
}
</style>
